import React, { useState } from 'react';
import { View, Text, TextInput, ScrollView, Pressable, ActivityIndicator, Alert, Modal, FlatList, TouchableOpacity } from 'react-native';
import { Stack, useRouter } from 'expo-router';
import { Ionicons } from '@expo/vector-icons';
import { Container } from '~/components/Container';
import { fetchUsers, createTheme } from '~/utils/auth/apiClient';

// 定义用户类型接口
interface User {
  userId: string;
  name: string;
  email?: string;
}

// 定义参与者类型接口
interface Participant {
  userId: string;
  role: string;
}

export default function NewThemeScreen() {
  const router = useRouter();
  const [title, setTitle] = useState('');
  const [description, setDescription] = useState('');
  
  // 各类型参与者状态
  const [contactParticipants, setContactParticipants] = useState<User[]>([]);
  const [proxyParticipants, setProxyParticipants] = useState<User[]>([]);
  
  // 搜索相关状态
  const [showContactSearch, setShowContactSearch] = useState(false);
  const [showProxySearch, setShowProxySearch] = useState(false);
  const [searchQuery, setSearchQuery] = useState('');
  const [searchResults, setSearchResults] = useState<User[]>([]);
  const [isSearching, setIsSearching] = useState(false);
  const [users, setUsers] = useState<User[]>([]);
  
  // Tab状态
  const [activeTab, setActiveTab] = useState('basic'); // basic, contacts, proxies
  
  const [submitting, setSubmitting] = useState(false);
  const [error, setError] = useState('');

  // 获取用户数据
  React.useEffect(() => {
    const loadUsers = async () => {
      try {
        setError('');
        const data = await fetchUsers();
        
        console.log('获取用户数据:', data);
        if (data.message === 'success') {
          setUsers(data.data);
        } else {
          console.error('获取用户数据失败', data.error);
          setError('获取用户数据失败: ' + (data.error || '未知错误'));
        }
      } catch (error) {
        console.error('获取用户数据时发生错误', error);
        setError('获取用户数据时发生错误: ' + (error instanceof Error ? error.message : String(error)));
      }
    };
    loadUsers();
  }, []);

  // 处理用户搜索
  const handleSearchChange = (text: string) => {
    setSearchQuery(text);
    if (text.length > 1) {
      searchUsers(text);
    } else {
      setSearchResults([]);
    }
  };

  // 搜索用户
  const searchUsers = async (query: string) => {
    setIsSearching(true);
    try {
      const filteredUsers = users.filter(user => 
        user.name.toLowerCase().includes(query.toLowerCase()) ||
        (user.email && user.email.toLowerCase().includes(query.toLowerCase()))
      );
      setSearchResults(filteredUsers);
    } catch (error) {
      console.error('搜索用户失败:', error);
      Alert.alert('错误', '搜索用户失败');
    } finally {
      setIsSearching(false);
    }
  };

  // 选择用户
  const handleSelectUser = (user: User, isProxy: boolean = false) => {
    if (isProxy) {
      if (!proxyParticipants.some(u => u.userId === user.userId)) {
        setProxyParticipants([...proxyParticipants, user]);
      }
    } else {
      if (!contactParticipants.some(u => u.userId === user.userId)) {
        setContactParticipants([...contactParticipants, user]);
      }
    }
    setSearchQuery('');
    setSearchResults([]);
  };

  // 移除选中的用户
  const handleRemoveUser = (userId: string, isProxy: boolean = false) => {
    if (isProxy) {
      setProxyParticipants(proxyParticipants.filter(user => user.userId !== userId));
    } else {
      setContactParticipants(contactParticipants.filter(user => user.userId !== userId));
    }
  };

  // 渲染搜索模态框
  const renderSearchModal = (isProxy: boolean = false) => {
    const modalVisible = isProxy ? showProxySearch : showContactSearch;
    const setModalVisible = isProxy ? setShowProxySearch : setShowContactSearch;
    const selectedUsers = isProxy ? proxyParticipants : contactParticipants;
    
    return (
      <Modal
        visible={modalVisible}
        transparent
        animationType="slide"
        onRequestClose={() => setModalVisible(false)}
      >
        <View className="flex-1 justify-end bg-black/50">
          <View className="bg-white rounded-t-3xl p-6 h-3/4">
            <View className="items-center mb-4">
              <View className="w-10 h-1 bg-gray-300 rounded-full mb-2" />
              <Text className="text-xl font-bold">
                {isProxy ? '添加代理人' : '添加联系人'}
              </Text>
            </View>
            
            {/* 搜索框 */}
            <View className="mb-4">
              <View className="flex-row items-center border border-gray-300 rounded-lg px-3 py-2">
                <Ionicons name="search" size={20} color="#6B7280" />
                <TextInput
                  className="flex-1 ml-2"
                  placeholder="搜索用户..."
                  value={searchQuery}
                  onChangeText={handleSearchChange}
                />
              </View>
            </View>
            
            {/* 搜索结果 */}
            {isSearching ? (
              <ActivityIndicator size="small" color="#3B82F6" />
            ) : searchResults.length > 0 ? (
              <View className="mb-4 max-h-80">
                <Text className="text-sm text-gray-500 mb-2">搜索结果</Text>
                <FlatList
                  data={searchResults}
                  keyExtractor={(item) => item.userId}
                  renderItem={({ item }) => (
                    <TouchableOpacity 
                      className="flex-row items-center py-2 border-b border-gray-100"
                      onPress={() => handleSelectUser(item, isProxy)}
                    >
                      <View className="w-8 h-8 rounded-full bg-blue-100 items-center justify-center mr-2">
                        <Text className="text-blue-600 font-bold">
                          {item.name.charAt(0).toUpperCase()}
                        </Text>
                      </View>
                      <View>
                        <Text className="font-medium">{item.name}</Text>
                        <Text className="text-sm text-gray-500">{item.email || item.userId}</Text>
                      </View>
                    </TouchableOpacity>
                  )}
                />
              </View>
            ) : searchQuery.length > 0 ? (
              <Text className="text-gray-500 mb-4">未找到匹配的用户</Text>
            ) : null}
            
            {/* 已选择用户 */}
            <View className="mb-4 flex-1">
              <Text className="text-sm text-gray-500 mb-2">已选择 ({selectedUsers.length})</Text>
              <FlatList
                data={selectedUsers}
                keyExtractor={(item) => item.userId}
                renderItem={({ item }) => (
                  <View className="flex-row items-center justify-between py-2 border-b border-gray-100">
                    <View className="flex-row items-center">
                      <View className="w-8 h-8 rounded-full bg-blue-100 items-center justify-center mr-2">
                        <Text className="text-blue-600 font-bold">
                          {item.name.charAt(0).toUpperCase()}
                        </Text>
                      </View>
                      <View>
                        <Text className="font-medium">{item.name}</Text>
                        <Text className="text-sm text-gray-500">{item.email || item.userId}</Text>
                      </View>
                    </View>
                    <TouchableOpacity onPress={() => handleRemoveUser(item.userId, isProxy)}>
                      <Ionicons name="close-circle" size={20} color="#EF4444" />
                    </TouchableOpacity>
                  </View>
                )}
              />
            </View>
            
            {/* 按钮区域 */}
            <View className="flex-row mt-4">
              <TouchableOpacity 
                className="flex-1 py-3 bg-gray-200 rounded-lg mr-2 items-center"
                onPress={() => {
                  setModalVisible(false);
                  setSearchQuery('');
                  setSearchResults([]);
                }}
              >
                <Text className="font-medium text-gray-700">取消</Text>
              </TouchableOpacity>
            </View>
          </View>
        </View>
      </Modal>
    );
  };

  // 表单验证
  const validateForm = () => {
    if (!title.trim()) {
      setError('请输入标题');
      Alert.alert('错误', '请输入标题');
      return false;
    }
    // if (contactParticipants.length === 0) {
    //   setError('请至少选择一位联系人');
    //   Alert.alert('错误', '请至少选择一位联系人');
    //   return false;
    // }
    return true;
  };

  // 处理提交
  const handleSubmit = async () => {
    if (!validateForm()) return;

    setSubmitting(true);
    setError('');
    
    try {
      // 合并不同角色的参与者，并添加角色标识
      const allParticipants = [
        ...contactParticipants.map(p => ({ 
          userId: p.userId,
          role: 'contributor' // 普通联系人
        })),
        ...proxyParticipants.map(p => ({ 
          userId: p.userId,
          role: 'proxy' // 代理人
        }))
      ];

      const themeData = {
        theme_name: title.trim(),
        theme_content: description.trim(),
        participants: allParticipants
      };

      console.log('创建主题:', themeData);

      // 使用API客户端创建主题
      const result = await createTheme(
        title.trim(),
        description.trim(),
        allParticipants
      );
      
      Alert.alert(
        '成功',
        '主题创建成功',
        [
          {
            text: '确定',
            onPress: () => router.push('/themes')
          }
        ]
      );
    } catch (error) {
      setError('创建报销主题失败: ' + (error instanceof Error ? error.message : String(error)));
      Alert.alert('错误', '创建报销主题失败: ' + (error instanceof Error ? error.message : String(error)));
      console.error('提交错误:', error);
    } finally {
      setSubmitting(false);
    }
  };

  // 渲染Tab内容
  const renderTabContent = () => {
    switch (activeTab) {
      case 'basic':
        return (
          <View className="gap-4">
            <View>
              <Text className="text-gray-700 font-medium mb-1">标题 <Text className="text-red-500">*</Text></Text>
              <TextInput
                className="bg-white border border-gray-300 rounded-lg p-3 text-base"
                placeholder="例如：2024年第一季度市场部差旅费"
                value={title}
                onChangeText={setTitle}
              />
            </View>

            <View>
              <Text className="text-gray-700 font-medium mb-1">描述</Text>
              <TextInput
                className="bg-white border border-gray-300 rounded-lg p-3 text-base"
                placeholder="请输入报销主题的详细描述"
                value={description}
                onChangeText={setDescription}
                multiline
                numberOfLines={3}
                textAlignVertical="top"
              />
            </View>
          </View>
        );

      case 'contacts':
        return (
          <View className="gap-4">
            <Text className="text-gray-600 mb-2">添加报销主题的联系人，他们将能够上传和管理发票。</Text>
            
            <View>
              <Text className="text-gray-700 font-medium mb-1">联系人 <Text className="text-red-500">*</Text></Text>
              <TouchableOpacity
                className="bg-white border border-gray-300 rounded-lg p-3 flex-row items-center justify-between"
                onPress={() => setShowContactSearch(true)}
              >
                <View className="flex-row items-center">
                  <Ionicons name="people-outline" size={20} color="#6B7280" />
                  <Text className="ml-2 text-gray-600">
                    {contactParticipants.length > 0 
                      ? `已选择 ${contactParticipants.length} 位联系人`
                      : '请选择联系人'}
                  </Text>
                </View>
                <Ionicons name="chevron-forward" size={20} color="#6B7280" />
              </TouchableOpacity>

              {contactParticipants.length > 0 && (
                <View className="mt-2">
                  {contactParticipants.map((user) => (
                    <View key={user.userId} className="flex-row items-center justify-between bg-gray-50 p-2 rounded-lg mb-1">
                      <View className="flex-row items-center">
                        <View className="w-8 h-8 rounded-full bg-blue-100 items-center justify-center mr-2">
                          <Text className="text-blue-600 font-bold">
                            {user.name.charAt(0).toUpperCase()}
                          </Text>
                        </View>
                        <View>
                          <Text className="font-medium">{user.name}</Text>
                          <Text className="text-sm text-gray-500">{user.email || user.userId}</Text>
                        </View>
                      </View>
                      <TouchableOpacity onPress={() => handleRemoveUser(user.userId)}>
                        <Ionicons name="close-circle" size={20} color="#EF4444" />
                      </TouchableOpacity>
                    </View>
                  ))}
                </View>
              )}
            </View>
          </View>
        );

      case 'proxies':
        return (
          <View className="gap-4">
            <Text className="text-gray-600 mb-2">添加报销主题的代理人，他们将能够代表其他人上传和管理发票。</Text>
            
            <View>
              <Text className="text-gray-700 font-medium mb-1">代理人</Text>
              <TouchableOpacity
                className="bg-white border border-gray-300 rounded-lg p-3 flex-row items-center justify-between"
                onPress={() => setShowProxySearch(true)}
              >
                <View className="flex-row items-center">
                  <Ionicons name="person-outline" size={20} color="#6B7280" />
                  <Text className="ml-2 text-gray-600">
                    {proxyParticipants.length > 0 
                      ? `已选择 ${proxyParticipants.length} 位代理人`
                      : '请选择代理人'}
                  </Text>
                </View>
                <Ionicons name="chevron-forward" size={20} color="#6B7280" />
              </TouchableOpacity>

              {proxyParticipants.length > 0 && (
                <View className="mt-2">
                  {proxyParticipants.map((user) => (
                    <View key={user.userId} className="flex-row items-center justify-between bg-gray-50 p-2 rounded-lg mb-1">
                      <View className="flex-row items-center">
                        <View className="w-8 h-8 rounded-full bg-blue-100 items-center justify-center mr-2">
                          <Text className="text-blue-600 font-bold">
                            {user.name.charAt(0).toUpperCase()}
                          </Text>
                        </View>
                        <View>
                          <Text className="font-medium">{user.name}</Text>
                          <Text className="text-sm text-gray-500">{user.email || user.userId}</Text>
                        </View>
                      </View>
                      <TouchableOpacity onPress={() => handleRemoveUser(user.userId, true)}>
                        <Ionicons name="close-circle" size={20} color="#EF4444" />
                      </TouchableOpacity>
                    </View>
                  ))}
                </View>
              )}
            </View>

            <View className="flex-row justify-between mt-6">
              <Pressable
                onPress={() => setActiveTab('contacts')}
                className="py-3 px-4 rounded-lg bg-gray-200"
              >
                <Text className="text-gray-800 font-medium text-lg text-center">上一步</Text>
              </Pressable>
            </View>
          </View>
        );
      
      default:
        return null;
    }
  };

  // 渲染Tab按钮
  const renderTabButtons = () => {
    const tabs = [
      { key: 'basic', label: '基本信息', icon: 'document-text-outline' },
      { key: 'contacts', label: '联系人', icon: 'people-outline', count: contactParticipants.length },
      { key: 'proxies', label: '代理人', icon: 'person-outline', count: proxyParticipants.length },
    ];

    return (
      <View className="flex-row border-b border-gray-200 mb-4">
        {tabs.map((tab) => (
          <Pressable
            key={tab.key}
            onPress={() => setActiveTab(tab.key)}
            className={`flex-1 py-3 flex-row items-center justify-center ${
              activeTab === tab.key ? 'border-b-2 border-blue-500' : ''
            }`}
          >
            <Ionicons 
              name={tab.icon as any} 
              size={18} 
              color={activeTab === tab.key ? '#3b82f6' : '#6b7280'} 
              style={{ marginRight: 6 }}
            />
            <Text 
              className={`${
                activeTab === tab.key ? 'text-blue-500 font-medium' : 'text-gray-600'
              }`}
            >
              {tab.label} {tab.count !== undefined && tab.count > 0 ? `(${tab.count})` : ''}
            </Text>
          </Pressable>
        ))}
      </View>
    );
  };

  return (
    <>
      <Stack.Screen options={{ 
        title: '新建报销主题',
        headerBackTitle: '返回'
      }} />
      <ScrollView className="flex-1 bg-gray-50">
        <Container>
          <View className="gap-4 py-4">
            {error ? (
              <View className="bg-red-50 p-3 rounded-md mb-2">
                <Text className="text-red-600">{error}</Text>
              </View>
            ) : null}

            {renderTabButtons()}
            {renderTabContent()}

            <View className="mt-6 pt-4 border-t border-gray-200">
              <View className="flex-row justify-between">
                <Pressable
                  onPress={() => router.back()}
                  className="py-3 px-5 rounded-lg bg-white border border-gray-300"
                >
                  <Text className="text-gray-700 font-medium">取消</Text>
                </Pressable>
                
                <Pressable
                  onPress={handleSubmit}
                  disabled={submitting}
                  className={`py-3 px-5 rounded-lg ${submitting ? 'bg-blue-300' : 'bg-blue-500'}`}
                >
                  <View className="flex-row justify-center items-center">
                    {submitting && <ActivityIndicator size="small" color="white" style={{ marginRight: 10 }} />}
                    <Text className="text-white font-bold">{submitting ? '创建中...' : '创建主题'}</Text>
                  </View>
                </Pressable>
              </View>
            </View>
          </View>
        </Container>
      </ScrollView>

      {/* 搜索模态框 */}
      {renderSearchModal(false)}
      {renderSearchModal(true)}
    </>
  );
}